package com.zhangxin.aiInterview.manager.asr;

import org.java_websocket.client.WebSocketClient;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.ConcurrentHashMap;

/**
 * WebSocket连接管理器
 * 管理用户建立的所有ASR ws连接
 */
public class ASRWsManager {

    // Key: 用户ID, Value: 单个WebSocket连接
    private static final ConcurrentHashMap<Long, WebSocketClient> asrConnections = new ConcurrentHashMap<>();

    /**
     * 添加或更新连接
     * @param userId 用户唯一标识
     * @param ws WebSocket连接对象
     */
    public static void addOrUpdateConnection(Long userId, WebSocketClient ws) {
        // 先关闭旧连接（避免泄漏）
        WebSocketClient oldWs = asrConnections.get(userId);
        if (oldWs != null) {
            oldWs.close(1000, "Connection replaced");
        }
        asrConnections.put(userId, ws);
    }

    /**
     * 获取连接
     * @param userId
     * @return
     */
    public static WebSocketClient getConnection(Long userId) {
        return asrConnections.get(userId);
    }

    /**
     * 移除连接
     * @param userId 用户ID
     */
    public static void removeConnection(Long userId) {
        WebSocketClient ws = asrConnections.get(userId);
        if (ws != null) {
            ws.close(1000, "Connection removed");
        }
        asrConnections.remove(userId);
    }
}